<template>
    <Modal
        title="租客批量授权"
        :value="show"
        width="600"
        @on-visible-change="setVisibility">

        <Alert>说明：门禁授权有效期 同 租客的租约有效期。</Alert>

        <div class="flex flex-align-center margin-bottom-20">
            <span style="width:5em">搜索关键字</span>
            <i-input v-model="keyword" @keydown.enter.native="handleSearch" class="flex-auto" style="margin: 0 10px" placeholder="姓名/手机号码/房间号"></i-input>
            <i-button @click="handleSearch">搜索</i-button>
        </div>

        <div class="margin-bottom-10">
            <i-button size="small" @click="handleSelectAll">选中当前页全部数据</i-button>
        </div>

        <Table
            border
            :data="pageData"
            :columns="columns"
            :loading="loading">
        </Table>

        <div class="text-center margin-top-10">
            <Page
                style="margin: 0"
                show-total
                :current.sync="pagination.current"
                :total="pagination.total"
                :page-size="pagination.limit"
            />
        </div>

        <Row slot="footer">
            <Button type="text" @click="setVisibility(false)">取消</Button>
            <Button type="primary" @click="handleSubmit" :loading="submiting">确定</Button>
        </Row>
    </Modal>
</template>

<script>
    import debounce from 'lodash/debounce'
import { Checkbox } from 'iview'; // eslint-disable-line
    import { http, api } from '@/libs/http'

export default {
      name: 'm3-auth-batch',
      props: {
        show: Boolean,
        datas: Object,
        roomId: Number,
        deviceId: Number
      },
      data () {
        return {
          loading: false,
          submiting: false,
          keyword: '',
          pagination: {
            current: 1,
            total: 0,
            limit: 5
          },
          /** 全部租客数据, selected都更改到这里 */
          allData: [],
          /** 当前符合条件的列表数据, pageData显示在table中 */
          tableData: [],
          selected: [],
          columns: [
            {
              title: ' ',
              width: 60,
              align: 'center',
              render: (h, { row }) => {
                return (
                  <Checkbox
                    value={row.selected}
                    onInput={val => { this.handleCheck(row.identifyNumber, val) }}
                  >
                  </Checkbox>
                )
              }
            },
            { title: '姓名', key: 'tenant_name' },
            { title: '手机号码', key: 'phone' },
            { title: '入住房间', key: 'room_name' }
          ]
        }
      },
      computed: {
        /** 组件当前显示的数据 */
        pageData () {
          const { tableData } = this
          const { current, limit } = this.pagination
          const offset = (current - 1) * limit
          return tableData.slice(offset, offset + limit)
        }
      },
      watch: {
        show (n) {
          if (n) {
            this.fetchTenant()
          } else {
            this.keyword = ''
            this.pagination.total = 0
            this.pagination.current = 1
          }
        }
      },
      methods: {
        setVisibility (val) {
          this.$emit('update:show', val)
        },
        handleSubmit () {
          const tenants = this.allData.reduce((result, { tenant_id, lease_id, selected }) => {
            return selected
              ? result.concat([{ tenant_id, lease_id }])
              : result
          }, [])
          if (!tenants.length) {
            this.$Message.info('请选择租客')
          } else {
            this.submit(tenants)
          }
        },
        async submit (tenants) {
          try {
            this.submiting = true
            const res = await http.req(api.m3_multi_auth_add, [this.roomId, this.deviceId], { tenants })
            if (res) {
              this.$Message.success('添加成功')
              this.$emit('refresh')
              this.setVisibility(false)
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.submiting = false
          }
        },
        handleSearch: debounce(function () {
          this.pagination.current = 1
          this.search()
        }),
        search () {
          const keyword = this.keyword.trim()
          if (keyword === '') {
            this.setTableData(this.allData)
          } else {
            const data = this.allData.filter(({ tenant_name, phone, room_name }) => {
              return tenant_name.includes(keyword) || phone.includes(keyword) || room_name.includes(keyword)
            })
            this.setTableData(data)
          }
        },
        /**
             * @param {string} identifyNumber 获取租客时的组合id
             */
        handleCheck (identifyNumber, result) {
          const index = this.allData.findIndex(item => item.identifyNumber === identifyNumber)
          if (index + 1) {
            this.$set(this.allData[index], 'selected', result)
            this.search()
          }
        },
        handleSelectAll () {
          this.pageData.forEach(item => {
            if (!item.selected) {
              this.handleCheck(item.identifyNumber, true)
            }
          })
        },
        handleClose (e, index) {
          this.selected.splice(index, 1)
        },
        async fetchTenant () {
          try {
            this.loading = true
            const res = await http.req(api.m3_authorizable_tenants_list, [this.roomId, this.deviceId], null)
            if (res) {
              res.forEach(item => {
                /** 租客入住不同房间存在多条记录 */
                item.identifyNumber = `${item.lease_id}${item.tenant_id}`
                item.selected = false
              })
              this.allData = res
              this.setTableData(res)
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        },
        setTableData (data) {
          this.tableData = data
          this.pagination.total = data.length
        }
      }
    }
</script>